const dayjs = require("dayjs");
const jwt = require("jsonwebtoken");
// 生成队长模块处理函数
exports.setCaptain = async (req, res, next) => {
  try {
    // 传值修改队长处理模块
    const { id, team_id } = req.query;
    if (id && team_id) {
      // 查询库里是否存在用户信息
      const sqlCaption = `select user_name from fa_users WHERE team_id=? AND id=?`;
      const sqlResult = await global.query(sqlCaption, [team_id, id]);
      if (sqlResult.length > 0) {
        const user_name = sqlResult[0].user_name;
        // 更新队伍表中的队长ID  查表
        const sqls = [
          "UPDATE fa_team SET captain_id = ?, captain_name = ? WHERE team_id = ?",
          "UPDATE fa_users SET role = ? WHERE team_id = ? AND  role = 1",
          "UPDATE fa_users SET role = ? WHERE id= ? ",
        ];
        const params = [
          [id, user_name, team_id],
          [0, team_id],
          [1, id],
        ];
        await global.runTransaction(sqls, params).then((result) => {
          if (result.affectedRows != 0) {
            return res.send({ code: 200, msg: "success", data: result.length });
          }
        });
      } else {
        return res.cc("暂无用户信息");
      }
    } else {
      try {
        // 根据点赞量高的人生成为队长
        // 查询所有的队伍图片点赞高的用户
        const sql = `SELECT u.user_name, i.id, i.team_id,i.user_id, i.likes FROM fa_images i 
        JOIN fa_users u ON  i.user_id = u.id WHERE i.type = 1`;
        const captainRes = await global.query(sql);
        const result = captainRes.reduce((groups, obj) => {
          const group = obj.team_id;
          if (!groups[group]) {
            groups[group] = [];
          }
          groups[group].push(obj);
          return groups;
        }, {});
        for (const group in result) {
          result[group].sort((a, b) => a.likes - b.likes);
        }
        const mySqls = [];
        const myParams = [];
        const teams = [];
        Object.keys(result).map(async (key) => {
          const item = result[key];
          const userId = item[0]["user_id"];
          const userName = item[0]["user_name"];
          const teamId = item[0]["team_id"];
          // 队伍只有一个人的情况
          if (item.length == 1) {
            myParams.push([userId, userName, teamId]);
            myParams.push([0, teamId]);
            myParams.push([1, userId]);
            teams.push(teamId);
            mySqls.push(
              "UPDATE fa_team SET captain_id = ?, captain_name = ? WHERE team_id = ?"
            );
            mySqls.push(
              "UPDATE fa_users SET role = ? WHERE team_id = ? AND  role = 1"
            );
            mySqls.push("UPDATE fa_users SET role = ? WHERE id = ?");
          } else if (item.length > 1) {
            // 多人情况
            item.sort((a, b) => a.likes - b.likes);
            if (item[0].likes != item[1].likes) {
              teams.push(teamId);
              myParams.push([userId, userName, teamId]);
              myParams.push([0, teamId]);
              myParams.push([1, userId]);
              mySqls.push(
                "UPDATE fa_team SET captain_id = ?, captain_name = ? WHERE team_id = ?"
              );
              mySqls.push(
                "UPDATE fa_users SET role = ? WHERE team_id = ? AND  role = 1"
              );
              mySqls.push("UPDATE fa_users SET role = ? WHERE id = ?");
            }
          }
        });
        if (mySqls.length) {
          await global.runTransaction(mySqls, myParams).then((result) => {
            if (result.affectedRows != 0) {
              return res.send({
                code: 200,
                msg: "success",
                data: teams.join(","),
              });
            }
          });
        } else {
          return res.send({ code: 200, msg: "没有可以生成的队长！" });
        }
      } catch (error) {
        await global.rollback; // 发生错误时回滚事务
        global.logger.error({
          status: 500,
          message: "设置队长时发生错误" + error,
        });
        return res.cc("设置队长时发生错误", error);
      }
    }
  } catch (err) {
    global.logger.error({
      status: 500,
      message: "error" + err,
    });
    return res.cc("err" + err);
  }
};
// 修改队伍昵称的模块处理函数
exports.updateNickName = (req, res, next) => {
  const { id, team_id } = req.user;
  const updated_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
  // 查询当前用户是否是队长身份
  const sql = `SELECT * from fa_users u WHERE u.role = 1 AND u.id=?`;
  global.query(sql, [id]).then((sqlRusult) => {
    if (sqlRusult.length > 0) {
      // 修改队伍昵名
      const { nick_name } = req.body;
      const update_sql = `UPDATE fa_team SET nick_name = ?, updated_time = ? WHERE captain_id=?`;
      global
        .query(update_sql, [nick_name, updated_time, id])
        .then((updateSqlResult) => {
          if (updateSqlResult.affectedRows != 0) {
            res.send({ code: 200, msg: "修改战队昵称成功" });
          } else {
            return res.cc("修改失败，请重新尝试！");
          }
        });
    } else {
      return res.cc("您不是队长身份，无法修改");
    }
  });
};
// 获取团队人员
exports.getTeamUsers = async (req, res, next) => {
  const { id, team_id } = req.user;
  const sql = `SELECT * FROM fa_team  WHERE  team_id = ?`;
  const teamResultData = await global.query(sql, [team_id]);
  let teamArr = {};
  if (teamResultData.length > 0) {
    teamArr = teamResultData[0];
  }
  const sql_0 = `SELECT * FROM fa_users  WHERE team_id  = ? AND is_login = 1`;
  const usersResultData = await global.query(sql_0, [team_id]);
  res.send({
    code: 200,
    msg: "success",
    data: { team_info: teamArr, list: usersResultData },
  });
};
